var adUser = 0; //所有广告主0 1测试
var beginTime = "";
var endTime = "";
var resourceTyp = 0; //资源类型：0全部，1保价保量，2保价不保量

var page = 1; //默认页数
var pageSize = 10; //每页条数
var total = 0; //总条数
//分页方法
function paging(page, pageSize, total) {
	page = Number(page);

	//最大页数
	var maxPage = Math.ceil(total / pageSize) || 1;
	if(page > maxPage) {
		//取值不能超过maxPage
		page = Math.min(page, maxPage);
		tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
	} else if(page < 1) {
		//取值不能小于1
		page = Math.max(page, 1);
		tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
	} else {
		//	当前页数
		$('.ui-paging-count').val(page);
		//首页的置灰处理
		$('.js-page-first').removeClass('ui-pager-disabled');
		//上一页
		$('.js-page-prev').removeClass('ui-pager-disabled').attr("data-page", page - 1);
		//下一页
		$('.js-page-next').removeClass('ui-pager-disabled').attr("data-page", page + 1);
		//最末页
		$('.js-page-last').removeClass('ui-pager-disabled').attr("data-page", maxPage);
		//总页数显示
		$('.js-page-total').text(maxPage);

		//当前显示多少页的处理
		$(".ui-select-pagesize").val(pageSize);
		//第一页的处理
		if(page == 1) {
			$(".js-page-first").addClass('ui-pager-disabled').attr("data-page", "");
			$(".js-page-prev").addClass('ui-pager-disabled').attr("data-page", "");
		}
		if(page == maxPage) {
			//最后一页的处理
			$(".js-page-last").addClass('ui-pager-disabled').attr("data-page", "");
			$(".js-page-next").addClass('ui-pager-disabled').attr("data-page", "");
		}
	}

};
//下拉选择分页条数的操作
$('.ui-select-pagesize').on("change", function() {
	pageSize = $(this).val();
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
});

//跳转到X页  blur
$(".ui-paging-count").on("blur", function() {
	page = $(this).val();
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
});

//上一页，下一页，首页，最末页的跳转
$('.ui-pager').on("click", function() {
	page = $(this).attr("data-page");
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
});

//角色名查找
//$('.clickFunc').on("click", function() {
//	roleName1 = $('#searchRalename').val();
//	tiaozhuan(param, page, pageSize, beginTime, endTime, type);
//});

function tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp) {
	var html = "";
	method = "post";
	datas = {
		page: page,
		pageSize: pageSize,
		beginTime: beginTime,
		endTime: endTime,
		adUser: adUser,
		resourceTyp: resourceTyp
	};
	getAgentMsg(param, method, datas);
//	console.log(dataResult);
	for(var i = 0; i < dataResult.data.rows.length; i++) {
		var istype = "";
		switch(dataResult.data.rows[i].resourceTyp) {
			case "1":
				istype = "保价保量";
				break;
			case "2":
				istype = "保价不保量";
				break;
			default:
				istype = "-";
		}
		html += "<tr>";
		html += "<td>" + dataResult.data.rows[i].adUserName + "</td>";
		html += "<td>" + istype + "</td>";
		html += "<td>" + dataResult.data.rows[i].balance + "</td>";
		html += "<td>" + dataResult.data.rows[i].univalent + "</td>";
		html += "<td>" + dataResult.data.rows[i].displayNum + "</td>";
		html += "<td>" + dataResult.data.rows[i].clickNum + "</td>";
		html += "<td>" + dataResult.data.rows[i].clickRate + "</td>";
		html += "</tr>";
	}
	$(".roleList").html(html);
	//之后处理分页
	total = dataResult.data.total;
	paging(page, pageSize, total);
}
//下载文件
function download(){
	var param2 = "/agency/agAdContract/acReport";
	var method2 = "post";
	var resourceTypkl=$("#isTradeType").attr("data-wei");
	var adUserasd=$("#isTradeTypeG").attr("data-wei");
	var datas2 = {page: page, pageSize: 1000, beginTime: beginTime, endTime: endTime,resourceTyp:resourceTypkl,adUser:adUserasd};
	getAgentMsg2(param2,method2,datas2);
	var arr = dataResult2.data.rows || [];
    arr.forEach(function (v) {
    	if(v.resourceTyp == '1'){
    		v.resourceTyp ='保价保量';
    	}else if(v.resourceTyp == '2'){
    		v.resourceTyp ='保价不保量';
    	}
    })
	exportCsv({
        title: ['广告主名称','资源类型','成本(元)','单价(元)','展示量','点击量','点击率'],
        titleForKey: ['adUserName','resourceTyp','balance','univalent','displayNum','clickNum','clickRate'],
        data: dataResult2.data.rows,
    },"合约交易概况.csv");
}


//下拉选择类型
function clickFunc(obj) {
	$("#isTradeType").text($(obj).text()).attr("data-wei",$(obj).children().attr("data-wei"));
	resourceTyp = $(obj).children().attr("data-wei");
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
}

//下拉选择广告主
function clickFuncG(obj) {
	$("#isTradeTypeG").text($(obj).text()).attr("data-wei",$(obj).children().attr("data-wei"));
	adUser = $(obj).children().attr("data-wei");
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
}

//获取广告主
function guanggaoz() {
	var datass = {};
	var htmlG = "";
	$.ajax({
		url: url + "/agency/adUserInfoList",
		type: "post",
		dataType: 'json',
		data: JSON.stringify(datass),
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
			
			if(result.code == '0') {
				for(var i = 0; i < result.data.rows.length; i++) {
					htmlG += "<li onclick='clickFuncG(this)'>";
					htmlG += "<a href='javascript:void(0);' data-wei='"+result.data.rows[i].id+"'>"+result.data.rows[i].username+"</a>";
					htmlG += "</li>";
				}
				$("#guanggaoz").append(htmlG);
			}
		}

	});
}

//获取当前时间戳 reutrn YYYY-MM-DD
function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	//var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();

	if(month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if(strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
	return currentdate;
};
//传入一个  YYYYY-MM-DD  前推和后退数以天数
function nextDayFnc(beginTime, y, z) {
	var beginTime = beginTime;
	var beginTime2 = beginTime.split("-");
	var year = parseInt(beginTime2[0]);
	var month = parseInt(beginTime2[1]);
	var day = parseInt(beginTime2[2]);
	var myDate = new Date();
	var setYesDay = parseInt(myDate.setFullYear(year, month - 1, day));
	if(z == 1) {
		var yesterday = parseInt(setYesDay - 86400000 * y); //加减天数改变这个毫秒数
	} else if(z == 2) {
		var yesterday = parseInt(setYesDay + 86400000 * y); //z==1时为-  z==2时为+
	}
	var ds = new Date(yesterday);
	var oldYear = ds.getYear() + 1900;
	var oldMonth = ds.getMonth() + 1;
	if(oldMonth < 10) {
		oldMonth = "0" + oldMonth;
	} else {
		oldMonth = oldMonth;
	}
	var oldDay = ds.getDate();
	if(oldDay < 10) {
		oldDay = "0" + oldDay;
	} else {
		oldDay = oldDay;
	}
	var yesDay = oldYear + "-" + oldMonth + "-" + oldDay;
	return yesDay;
};
//传入 YYYYY-MM-DD 转成 yyyy年mm月dd日
function parseDate(date) {
	var newDate = date.split("-");
	return newDate[0] + "年" + newDate[1] + "月" + newDate[2] + "日";
}
var date = new Date();
var lastWeek = new Date(date.getTime() - 6 * 24 * 3600 * 1000);
var lastTwo = new Date(date.getTime() - 13 * 24 * 3600 * 1000);
var tody = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
lastWeek = lastWeek.getFullYear() + "-" + (lastWeek.getMonth() + 1) + "-" + lastWeek.getDate();
lastTwo = lastTwo.getFullYear() + "-" + (lastTwo.getMonth() + 1) + "-" + lastTwo.getDate();
var yesterday = nextDayFnc(getNowFormatDate(), 1, 1);
// 借用nextDayFnc方法将XXXX-X-X转化成XXXX-0X-0X格式
tody = nextDayFnc(tody, 0, 1);
lastWeek = nextDayFnc(lastWeek, 0, 1);
lastTwo = nextDayFnc(lastTwo, 0, 1);
$(".tody_btn").html("全部时间段");
$(".tody_day").html("今日：" + parseDate(tody));
$(".yesterday_day").html("昨日：" + parseDate(yesterday));
$(".lastWeek_day").html("最近7日：" + parseDate(lastWeek) + " — " + parseDate(tody));
$(".lastTwo_day").html("最近14日：" + parseDate(lastTwo) + " — " + parseDate(tody));

//点击事件
function selectDate(d, obj) {
	if(d == 1) {
		beginTime = tody;
		endTime = tody;
		$(".tody_btn").html($(obj).find("a").html());
	} else if(d == 2) {
		beginTime = yesterday;
		endTime = yesterday;
		$(".tody_btn").html($(obj).find("a").html());
	} else if(d == 3) {
		beginTime = lastWeek;
		endTime = tody;
		$(".tody_btn").html($(obj).find("a").html());
	} else if(d == 4) {
		beginTime = lastTwo;
		endTime = tody;
		$(".tody_btn").html($(obj).find("a").html());
	} else if(d == 5) {
		var test1 = $("#test1").val();
		var test2 = $("#test2").val();
		if(!test1) {
			layer.msg("请先选择时间");
			return false;
		}
		if(!test2) {
			layer.msg("请先选择时间");
			return false;
		}
		beginTime = test1;
		endTime = test2;
		$(".tody_btn").html("时间为：" + parseDate(test1) + " — " + parseDate(test2));
		$(".tody_btn").parent().removeClass("open");
	}

	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);
}

//获取余额通用
function getAllMoney() {
	var dataM = {};
	$.ajax({
		url: url + "/sys/account",
		type: "post",
		dataType: 'json',
		data: JSON.stringify(dataM),
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {

			if(result.code == '0') {

				$(".allBalance").text(result.data.amount); //账户余额
				$(".usableBalance").text(result.data.actAmount); //账户余额

			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
}

//合约交易上面4个数据

	$.ajax({
		url: url + "/agency/agAdContract/agAdContractInfo",
		type: "post",
		dataType: 'json',
//		data: JSON.stringify(dataM),
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
			console.log(result);
			if(result.code == '0') {			
				var data=result.data.today;
				$(".Nicejiaoyi").html(data.balance);
				$(".Nicelirun").html(data.profit);
				$(".Nicelilv").html(data.profitrate);
				$(".Niceshouru").html(data.income);
				var data1=result.data.eve;
				$(".Nicejiaoyi3").html(data1.balance);
				$(".Nicelirun3").html(data1.profit);
				$(".Nicelilv3").html(data1.profitrate);
				$(".Niceshouru3").html(data1.income);
				var data2=result.data.yesterday;
				$(".Nicejiaoyi1").html(data2.balance);
				$(".Nicelirun1").html(data2.profit);
				$(".Nicelilv1").html(data2.profitrate);
				$(".Niceshouru1").html(data2.income);
			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});


//初始化加载数据
window.onload = function() {
	//初始化时间控件
	laydate.render({
		elem: '#test1' //指定元素
	});
	laydate.render({
		elem: '#test2'
	});
	getAllMoney();
	guanggaoz();
	param = "/agency/agAdContract/acReport";
	tiaozhuan(param, page, pageSize, beginTime, endTime, adUser, resourceTyp);

}